﻿using Basic.HrCollect;
using Basic.HrModel.DB;
using Basic.HrModel.EmpPost;
using Basic.HrRemoteModel.EmpPost.Model;
using Basic.HrService.Interface;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;

namespace Basic.HrService.lmpl
{
    internal class EmpPostService : IEmpPostService
    {
        private readonly IEmpPostCollect _Service;
        private readonly IDeptCollect _Dept;
        private readonly IPostDicItemCollect _PostDic;
        private readonly ICompanyCollect _Company;
        public EmpPostService ( IEmpPostCollect service,
            IDeptCollect dept,
            ICompanyCollect company,
            IPostDicItemCollect post )
        {
            this._Company = company;
            this._PostDic = post;
            this._Dept = dept;
            this._Service = service;
        }

        public long Add ( EmpPostAdd add )
        {
            EmpPostAddDto data = add.ConvertMap<EmpPostAdd, EmpPostAddDto>();
            data.UnitId = this._Dept.GetUnitId(add.DeptId);
            return this._Service.Add(data);
        }

        public void Delete ( long id )
        {
            DBEmpPost post = this._Service.Get(id);
            this._Service.Delete(post);
        }
        public EmpPostData Get ( long id )
        {
            return this._Service.Get<EmpPostData>(id);
        }
        public EmpPostDatum[] Gets ( long empId, long companyId )
        {
            long[] ids = this._Company.GetSubIds(companyId).Add(companyId);
            DBEmpPost[] posts = this._Service.GetEmpPost<DBEmpPost>(empId, ids);
            if ( posts.IsNull() )
            {
                return null;
            }
            EmpPostDatum[] dtos = posts.ConvertMap<DBEmpPost, EmpPostDatum>();
            long[] deptId = dtos.ConvertAll(c => c.DeptId);
            deptId = deptId.Add(dtos.ConvertAll(c => c.UnitId));
            Dictionary<long, string> comNames = this._Company.GetNames(dtos.Distinct(c => c.CompanyId));
            Dictionary<long, string> deptName = this._Dept.GetDeptName(deptId);
            Dictionary<string, string> postNames = this._PostDic.GetPostName(dtos.ConvertAll(c => c.PostCode));
            dtos.ForEach(c =>
            {
                c.CompanyName = comNames.GetValueOrDefault(c.CompanyId);
                c.DeptName = deptName.GetValueOrDefault(c.DeptId);
                c.UnitName = deptName.GetValueOrDefault(c.UnitId);
                c.Post = postNames.GetValueOrDefault(c.PostCode);
            });
            return dtos;
        }
    }
}
